package org.jeecg.modules.yks.mqtt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.yks.bas.entity.YksTopicData;
import org.jeecg.modules.yks.bas.service.impl.YksTopicDataServiceImpl;
import org.jeecg.modules.yks.dev.entity.YksEquipment;
import org.jeecg.modules.yks.dev.entity.YksEquipmentConfigurationPlc;
import org.jeecg.modules.yks.dev.mapper.YksEquipmentConfigurationPlcMapper;
import org.jeecg.modules.yks.dev.mapper.YksEquipmentMapper;
import org.jeecg.modules.yks.mng.entity.YksEquipmentRundata;
import org.jeecg.modules.yks.mng.entity.YksPlcParameter;
import org.jeecg.modules.yks.mng.mapper.YksEquipmentRundataMapper;
import org.jeecg.modules.yks.mng.mapper.YksPlcParameterMapper;
import org.jeecg.modules.yks.mqtt.service.MqttReceiveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;


import java.util.Date;
import java.util.Map;
import java.util.Random;

/**
 * 消息接收实现
 * 
 * @author weir
 *
 *         2019年6月19日 上午9:58:41
 */
@Slf4j
@Service
public class MqttReceiveServiceImpl implements MqttReceiveService {

	@Autowired
	private YksTopicDataServiceImpl yksTopicDataService;

	@Autowired
	private YksEquipmentMapper yksEquipmentMapper;

	@Autowired
	private YksEquipmentConfigurationPlcMapper yksEquipmentConfigurationPlcMapper;

	@Autowired
	private YksPlcParameterMapper yksPlcParameterMapper;

	@Autowired
	private YksEquipmentRundataMapper yksEquipmentRundataMapper;

	@Value("${mqtt.dataIntervalTime}")
	private int dataIntervalTime;

	final private String SPLIT_CHAR = "/";

	@Async
	@Override
	public void handlerMqttMessage(String topic, String jsonData) {
		log.info("this topic is ： " + topic + " ,this data : " + jsonData);
		YksTopicData yksTopicData = new YksTopicData();
		yksTopicData.setTopic(topic);
		yksTopicData.setJsonData(jsonData);
		yksTopicData.setTimeStamp(new Date());
		yksTopicDataService.save(yksTopicData);
		JSONObject mapType = JSON.parseObject(jsonData);
		String[] topics = topic.split(SPLIT_CHAR);
		String equipmentRdeeId = topics[topics.length - 2];
		YksEquipment yksEquipment = yksEquipmentMapper.selectOne(new QueryWrapper<YksEquipment>().eq("rdee_routeserialnumber",equipmentRdeeId));
		YksEquipmentConfigurationPlc yksEmPlc = null;
		YksPlcParameter yksPlc = null;
		JSONObject data=mapType.getJSONObject("data");
		for (Object obj : data.keySet()){
			yksEmPlc = yksEquipmentConfigurationPlcMapper.selectOne(new QueryWrapper<YksEquipmentConfigurationPlc>()
					.eq("equipment_id",yksEquipment.getId())
					.and(wrapper->wrapper.eq("parameter_plc_id",obj)));
			if(yksEmPlc==null)continue;
			yksPlc = yksPlcParameterMapper.selectById(yksEmPlc.getParameterId());
			YksEquipmentRundata rundata = new YksEquipmentRundata();
			rundata.setEquipmentCode(yksEquipment.getCode());
			rundata.setEquipmentId(yksEquipment.getId());
			rundata.setEquipmentName(yksEquipment.getName());
			rundata.setEquipmentType(yksEquipment.getEquipmentType());
			rundata.setRdeeRouteserialnumber(yksEquipment.getRdeeRouteserialnumber());
			rundata.setParameterGroup(yksEmPlc.getParameterGroup());
			rundata.setParameterId(yksEmPlc.getParameterId());
			rundata.setParameterName(yksEmPlc.getParameterName());
			rundata.setParameterPlcId(yksEmPlc.getParameterPlcId());
			rundata.setParameterScope(yksPlc.getParameterRange());
			rundata.setParameterType(yksEmPlc.getParameterType());
			rundata.setParameterRealtimedata(data.get(obj).toString());
			if(yksEmPlc.getIsRevise().equals(1)){
				try {
					String scope=yksPlc.getParamRefValue();
					String[] scopes=scope.split("-");
					if(scopes.length>1){
						Double min=Double.parseDouble(scopes[0]);
						Double max=Double.parseDouble(scopes[1]);
						Random random=new Random();
						Double value= random.nextDouble(max-min+1)+min;
						rundata.setParameterRevisedata(value.toString());
					}else
					{
						rundata.setParameterRevisedata(data.get(obj).toString());
					}
				}catch(Exception e)
				{
					rundata.setParameterRevisedata(data.get(obj).toString());
				}

				//修正

			}else {
				rundata.setParameterRevisedata(data.get(obj).toString());
			}
			yksEquipmentRundataMapper.insert(rundata);
		}
	}

	private static boolean checkSaveData(long cacheTime, int dataIntervalTime) {
		long ct = cacheTime + dataIntervalTime;
		return (System.currentTimeMillis() - ct) >= 0 ? true : false;
	}

}
